from sqlalchemy import Column, String, Integer
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

from init.mysql import engine

Base = declarative_base()


class CompanyDividend(Base):
    __tablename__ = 'company_dividend'

    id = Column(Integer, primary_key=True, autoincrement=True)
    code = Column(String(6))
    sdate = Column(String(10))
    give = Column(String(20))
    change = Column(String(20))
    send = Column(String(20))
    line = Column(String(20))
    cdate = Column(String(10))
    edate = Column(String(10))
    hdate = Column(String(10))

    def __init__(self, code, sdate, give, change, send, line, cdate, edate, hdate):
        self.code = code
        self.sdate = sdate
        self.give = give
        self.change = change
        self.send = send
        self.line = line
        self.cdate = cdate
        self.edate = edate
        self.hdate = hdate

    @staticmethod
    def insert_or_update(code,data_list):
        session = sessionmaker(bind=engine)()
        for data in data_list:
            existing_dividend = session.query(CompanyDividend).filter_by(code=code, cdate=data['cdate'], edate=data['edate']).first()
            if existing_dividend:
                existing_dividend.sdate = data['sdate']
                existing_dividend.give = data['give']
                existing_dividend.change = data['change']
                existing_dividend.send = data['send']
                existing_dividend.line = data['line']
                existing_dividend.cdate = data['cdate']
                existing_dividend.edate = data['edate']
                existing_dividend.hdate = data['hdate']
            else:
                company_dividend = CompanyDividend(code, data['sdate'], data['give'], data['change'], data['send'], data['line'], data['cdate'], data['edate'], data['hdate'])
                session.add(company_dividend)
        session.commit()


Base.metadata.create_all(engine)
